<?php

include_once "Model.php";

class Release_ extends Model {

    public function Release_($attr=null){ $this->table_name = RELEASE_TABLE; parent::__construct($attr); }
    
    public function getDetails(){
      $q = "SELECT r.id, r.title AS name, r.mb_id, r.coverimage, r.time_added, a.id AS artist_id, a.picture, a.name AS artist_name," .
           "COUNT( DISTINCT u2f.user_id ) AS favs_no
            FROM (".RELEASE_TABLE." r, ".TRACK_TABLE." t, ".ARTIST_TABLE." a)
            LEFT JOIN ".USER2FAV_TABLE." u2f ON (t.id = u2f.track_id)
            WHERE r.id = {$this->attributes['id']}
            AND t.release_id = r.id 
            AND r.artist_id = a.id
            GROUP BY t.release_id";	
      //echo $q;
      $tracks_stats = "SELECT SUM( t.played_times ) AS total_played,COUNT( t.id ) AS tracks_no FROM ".TRACK_TABLE." t WHERE t.release_id = {$this->attributes['id']}";
      
      $res = $this->SQL->query($q)->fetchObject();
      $tracks_stats_res = $this->SQL->query($tracks_stats)->fetchObject();
      $res->total_played = $tracks_stats_res->total_played;
      $res->tracks_no = $tracks_stats_res->tracks_no;
      
      return $res;
    }
    
    /*
     * @return: array of tracks SQL object
     */
    public function getTracks(){
      $tracks = array();
      $q = "SELECT t.title,t.time_added,t.id,t.played_times,COUNT(u2f.user_id) AS favs_no,u2f_.user_id AS fav_user
            
            FROM (".TRACK_TABLE." t, ".RELEASE_TABLE." r)
            LEFT JOIN ".USER2FAV_TABLE." u2f ON ( u2f.track_id = t.id )
            LEFT JOIN ".USER2FAV_TABLE." u2f_ ON (t.id = u2f_.track_id AND ".Session::factory()->getUserId()." = u2f_.user_id )
            WHERE r.id = {$this->attributes['id']}
            AND t.release_id = r.id
            GROUP BY t.id, u2f.track_id
            ORDER BY r.title ASC,t.played_times DESC,t.time_added DESC";
      
      $this->SQL->query($q);
      
      while($track=$this->SQL->fetchObject()){
      	array_push($tracks,$track);
      }
      
      return $tracks;
    }

}


?>
